<template>
  <div class="img-box" @click="zoom">
    <img
      src="https://fuyouplus.oss-cn-beijing.aliyuncs.com/image/loading.gif"
      alt="loading"
      v-show="!isLoaded"
    />
    <img :src="src" :alt="alt" @load="imgLoad" v-show="isLoaded" ref="myImg" />
  </div>
</template>

<script setup lang="ts">
import { defineProps, ref, shallowRef } from "vue"
import mediumZoom from "medium-zoom"
import bus from "@/eventBus"
const myImg = shallowRef<HTMLImageElement>()
const isLoaded = ref<boolean>(false)
let instance
defineProps<{
  src?: string
  alt?: string
}>()

const zoom = () => {
  instance.open()
  const overlay = document.querySelector(".medium-zoom-overlay") as HTMLDivElement
  const image_opened = document.querySelector(".medium-zoom-image--opened") as HTMLDivElement
  overlay.style.zIndex = "999"
  image_opened.style.zIndex = "999"
}

const imgLoad = () => {
  setTimeout(() => {
    isLoaded.value = true
    instance = mediumZoom(myImg.value, {
      background: bus.state.theme == "light" ? "#fff" : "#333",
    })
  }, 1000)
}
bus.on("theme", theme => {
  instance && instance.update({ background: theme == "light" ? "#fff" : "#333" })
})
</script>

<style lang="scss">
.img-box {
  display: inline-block;
  max-width: 100%;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: var(--bottom);

}
img {
  max-width: 100%;
  border-radius: 4px;
  transition: transform 0.7s ease-out;
}
.img-box:hover img {
  transform: scale(1.05);
}
.medium-zoom-image {
  cursor: zoom-in;
  transition: all 300ms;
}
.medium-zoom--open .medium-zoom-overlay {
  cursor: zoom-out;
  opacity: 1;
}

.medium-zoom-image--open {
  position: relative;
  cursor: zoom-out;
  will-change: transform;
}
</style>
